package com.hzlh.controller;

import com.hzlh.oss.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 数据库存相对路径，前台访问以参数url=img/banner/banner01.png调用
 */
@Controller
public class PictureController {
	
	@Autowired
	private OssService ossService;

	@Autowired
	private StringRedisTemplate redisTemplate;

	/**
	 * 服务器存储地址
	 */
	@Value("${system.url.img}")
	private String imgStorageUrl;
	private final static String IMAGE = ".+\\.(jpg|jpeg|png|bmp)$";
	
	/**
	 * 获取图片，注意防止服务器其他文件泄露
	 * 
	 * @param request
	 * @param response
	 * @param url
	 * @return
	 * @throws IOException 
	 */
//	@RequestMapping(value = "/img", method = RequestMethod.GET)
	@Deprecated
	public void getGameIcon(String url, HttpServletRequest request, HttpServletResponse response) {
		try {
			if(!StringUtils.isEmpty(url)){
				if(!url.contains("./") && !url.contains(".\\") && url.toLowerCase().matches(IMAGE)){
					//文件流读入返回
					FileInputStream fis = new FileInputStream(imgStorageUrl+url);
					ServletOutputStream ops = response.getOutputStream();
					int len = -1;
					byte[] datas = new byte[1024*100];
					while((len = fis.read(datas))!=-1){
						ops.write(datas,0,len);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
//	@PostMapping(value = "/img/upload")
//    @ResponseBody
	public Object upload(MultipartFile file) throws IOException {
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		String relfileName = new Date().getTime()+suffix;
		String filePath = imgStorageUrl+relfileName;

		File targetFile = new File(imgStorageUrl);
		if(!targetFile.exists()){
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath);
		out.write(file.getBytes());
		out.flush();
		out.close();
		Map<String,Object> map =new HashMap<String,Object>();
		map.put("url",relfileName);
		return map;
	}

	@PostMapping(value = "/img/upload")
	@ResponseBody
	public Object uploadToOss(MultipartFile file) throws IOException {
		String url = ossService.uploadLocalFileToOss("wecom", "wecom", file, true);
		Map<String, Object> map = new HashMap<>();
		map.put("url", url);
		return map;
	}

	@PostMapping(value = "/img/uploadBase64")
	@ResponseBody
	public Object uploadToOss(@RequestBody Map<String, Object> param) throws IOException {
        Integer sourceId = (Integer) param.get("sourceId");
		String imgBase64 = (String) param.get("imgBase64");
		String filePath = redisTemplate.opsForValue().get("idp_sourceImg_"+sourceId);
		if(filePath==null&&imgBase64!=null){
			String[] files = imgBase64.split("base64,");
			String baseFile = files[0];
			String[] baseFiles = baseFile.split(";");
			String suffixName = baseFiles[0].substring(11, baseFiles[0].length());		//后缀名
			BASE64Decoder decode = new BASE64Decoder();
			byte[] oldbyte = decode.decodeBuffer(files[1]);
			InputStream fileInputStream = new ByteArrayInputStream(oldbyte);
			filePath = ossService.uploadFileToOssWithInputStream("wecom","wecom",fileInputStream,"1."+suffixName);
			redisTemplate.opsForValue().set("idp_sourceImg_"+sourceId,filePath,1, TimeUnit.DAYS);
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("url",filePath);
		return map;
	}

}
